package com.hj.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hj.reggie.common.R;
import com.hj.reggie.domain.Category;
import com.hj.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author 37460
 */

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }


    /**
     * 新增分类
     *
     * @return 成功
     */

    @PostMapping
    public R<String> saveCategory(@RequestBody Category category) {
        log.info("category {}", category);
        category.setIsDeleted(0);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 查询所有菜品并分页接口
     *
     * @return 成功
     */

    @GetMapping("/page")
    public R<Page<Category>> selectCategory(Integer page, Integer pageSize) {
        log.info(page.toString());
        //创建分页对象
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //创建添加构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //使用升序进行排序,只查询IsDeleted等于1的
        queryWrapper.orderByAsc(Category::getSort);
        queryWrapper.eq(Category::getIsDeleted, 0);
        //执行查询
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);

    }

    /**
     * 删除分类
     *
     * @param ids 删除的菜品id
     * @return  删除成功
     */
    @DeleteMapping
    public R<String> deletedCategory(Long ids) {

        categoryService.remove(ids);

        return R.success("分类信息删除成功");
    }

    /**
     * 根据id修改分类信息
     *
     * @param category 分类信息
     * @return 注入R类型返回成功信息
     */

    @PutMapping
    public R<String> updateCategory(@RequestBody Category category) {
        log.info("修改分类的信息：{}", category);
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    /**
     * 根据条件查询分类
     * @return 返回 R.success(list) List<Category>
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //查询
        List<Category> list = categoryService.list(new LambdaQueryWrapper<Category>()
                //如果category.getType()不为空按照category.getType()查询
                .eq(category.getType() != null, Category::getType, category.getType())
                //按照getSort排序
                .orderByAsc(Category::getSort)
                //如果getSort一样按照getUpdateTime排序
                .orderByAsc(Category::getUpdateTime));
        return R.success(list);
    }
}
